<template>
  <div class="search_container">
    <!-- 搜索栏开始 -->
    <form action="/" class="searchForm">
      <van-search
        v-model="searchText"
        show-action
        placeholder="请输入搜索关键词"
        @search="onSearch"
        @cancel="onCancel"
        background="#3296fa"
        @focus="isResultsShow = false"
      />
    </form>
    <!-- 搜索栏结束 -->
    <!-- 搜索结果 -->
    <search-results
      v-if="isResultsShow"
      :q="searchText"
      :search-text="searchText"
    ></search-results>
    <!-- 搜索联想记忆 -->
    <search-suggest
      v-else-if="searchText"
      :searchText="searchText"
      @search="onSearch"
    ></search-suggest>
    <!-- 搜索历史记录 -->
    <search-history
      v-else
      :searchHistories="searchHistories"
      @clear-search-histories="searchHistories = []"
      @search="onSearch"
    ></search-history>
  </div>
</template>

<script>
import searchHistory from './components/search-history'
import searchSuggest from './components/search-suggest'
import searchResults from './components/search-results'
import { setItem, getItem } from '@/utils/storage.js'

export default {
  name: 'searchIndex',
  data() {
    return {
      searchText: '',
      isResultsShow: false,
      searchHistories: getItem('search_history') || []
    }
  },
  watch: {
    searchHistories(val) {
      // 同步到本地存储
      setItem('search_history', val)
    }
  },
  methods: {
    // 搜索框触发事件
    onSearch(val) {
      if (val.trim().length) {
        // 更新文本框内容
        this.searchText = val
        // 存储搜索历史记录
        // 要求：不要有重复历史记录 最新的排在前面
        const index = this.searchHistories.indexOf(val)
        if (index !== -1) {
          this.searchHistories.splice(index, 1)
        }
        this.searchHistories.unshift(val)
        // 触发搜索时 渲染搜索结果
        this.isResultsShow = true
      } else {
        this.$toast('内容不能为空')
      }
    },
    // 搜索框取消按钮
    onCancel() {
      this.$router.back()
    }
  },
  components: {
    searchHistory,
    searchSuggest,
    searchResults
  }
}
</script>

<style scoped lang="less">
.search_container {
  padding-top: 108px !important;
  .van-search__action {
    color: #fff;
  }
  .searchForm {
    position: fixed;
    left: 0;
    right: 0;
    top: 0;
    z-index: 1;
  }
}
</style>
